<?php

namespace Mlym\CodeGeneration\InitGeneration\Controller\Method;

use EasySwoole\EasySwoole\ServerManager;
use Mlym\CodeGeneration\ClassGeneration\MethodAbstract;

class GetClientIP extends MethodAbstract
{

    function addMethodBody()
    {
        $this->classGeneration->getPhpNamespace()->addUse(ServerManager::class);
        $method = $this->method;
        $method->addParameter('headerName')->setDefaultValue("x-real-ip");
        $method->setReturnType('string');
        $method->setBody(<<<BODY
\$server = ServerManager::getInstance()->getSwooleServer();
\$client = \$server->getClientInfo(\$this->request()->getSwooleRequest()->fd);
\$clientAddress = \$client['remote_ip'];
\$xri = \$this->request()->getHeader(\$headerName);
\$xff = \$this->request()->getHeader('x-forwarded-for');
if (\$clientAddress === '127.0.0.1') {
    if (!empty(\$xri)) {  // 如果有xri 则判定为前端有NGINX等代理
        \$clientAddress = \$xri[0];
    } elseif (!empty(\$xff)) {  // 如果不存在xri 则继续判断xff
        \$list = explode(',', \$xff[0]);
        if (isset(\$list[0])) \$clientAddress = \$list[0];
    }
}
return \$clientAddress;
BODY
        );
    }

    function getMethodName(): string
    {
        return 'clientRealIP';
    }

    public function addComment()
    {
        $comment = <<<COMMENT
获取IP地址
@param string \$headerName 获取IP的header字段名称
@return string
COMMENT;
        $this->method->addComment($comment);
    }
}